# -*- coding: utf-8 -*-
import json
import re
import string,time
from MsgProcess import MsgProcess, MsgType
import urllib.request
import package.SpeechSynthesis as SpeechSynthesis

class ChatRobot(MsgProcess):
    #self.say()方法在Text主循环连续播放百字以上内容时偶然异常发生提前停止的问题，未等待播放结束。故使用以下方法解决
    play =SpeechSynthesis.SpeechSynthesis(MsgProcess)

    def say(self,text):
        #print("菲菲执行自定义方法")
        self.send(MsgType=MsgType.Text, Receiver="Screen", Data=text)
        self.play.Text({"Data":text,'Sender':""})

    def qingyunke(self, text):
        " 青云客聊天机器人 "
        if text is None:
            return
        url = r'http://api.qingyunke.com/api.php?key=free&appid=0&msg='
        sendurl = url + text
        url = urllib.parse.quote(sendurl, safe=string.printable)
        page = urllib.request.urlopen(url)
        if page.getcode() == 200:
            html = page.read().decode("utf-8")
        else:
            self.say("网络异常,请重新说")

        # 判断返回数据是否是字典
        if re.sub(r'\{.*\}', "", str(html)) == "":
            res = json.loads(html)['content']
            self.say(re.sub(r'\{br\}', "", res ))

        else:
            self.say("识别异常,请重新说。")

    def Text(self, message):  
        self.say("进入陪聊，我是菲菲，您好请说：")

        while("菲菲聊天中..."):

            words = self.listen(4)

            if "退出聊天" in words or "结束聊天" in words  or "再见" in words:
                break

            if "你会什么" in words:
                self.qingyunke("help")
                time.sleep(1)
                continue

            if words:
                self.qingyunke(words)

            else:
                break
        
            time.sleep(1)

        self.say("菲菲结束陪聊，再见")
        self.Stop() 

